#include"Input.h"
#include<assert.h>

D3DXInput* D3DXInput::_dinputInstance = 0;

D3DXInput* D3DXInput::GetInstance()
{
	if (_dinputInstance == NULL)
		_dinputInstance = new D3DXInput;

	return _dinputInstance;
}

D3DXInput::D3DXInput()
{
	_di = NULL;
	_keyBoard = NULL;
	_keyUp = 0;
	_keyDown = 0;
}
bool D3DXInput::InitInput(HINSTANCE hInstance, HWND hWnd)
{
	HRESULT result;
	result = DirectInput8Create(
		hInstance,
		DIRECTINPUT_VERSION,
		IID_IDirectInput8,
		(VOID  **)&_di,
		NULL);
	assert(!FAILED(result));

	result = _di->CreateDevice(GUID_SysKeyboard, &_keyBoard, NULL);
	assert(!FAILED(result));
	result = _keyBoard->SetDataFormat(&c_dfDIKeyboard);
	result = _keyBoard->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);

	DIPROPDWORD dipdw;
	dipdw.diph.dwSize = sizeof(DIPROPDWORD);
	dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
	dipdw.diph.dwObj = 0;
	dipdw.diph.dwHow = DIPH_DEVICE;
	dipdw.dwData = KEYBOARD_BUFFER_SIZE;

	result = _keyBoard->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph);
	assert(!FAILED(result));

	result = _keyBoard->Acquire();
	assert(!FAILED(result));
	return true;
}
void D3DXInput::ProcessKeyBoard(HWND hWnd)
{
	if (!SUCCEEDED(_keyBoard->GetDeviceState(sizeof(KeyStates), KeyStates)))
	{
		//Keyboard deviced lost, try to re-acquire
		_keyBoard->Acquire();
	}
	if (IsKeyDown(DIK_ESCAPE))
	{
		//PostMessage(hWnd,WM_QUIT,0,0);
	}
	DWORD dwElements = KEYBOARD_BUFFER_SIZE;
	HRESULT hr = _keyBoard->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), KeyEvents, &dwElements, 0);

	// Scan through all data, check if the key is pressed or released
	for (DWORD i = 0; i < dwElements; i++)
	{
		int KeyCode = KeyEvents[i].dwOfs;
		int KeyState = KeyEvents[i].dwData;
		if ((KeyState & 0x80) > 0)
		{
			_keyDown = KeyCode;
		}
		else
		{
			_keyUp = KeyCode;
		}
	}
}

int D3DXInput::IsKeyDown(int KeyCode)
{
	return (KeyStates[KeyCode] & 0x80) > 0;
}

int D3DXInput::GetKeyDown()
{
	int tam = _keyDown;
	_keyDown = 0;
	return tam;
}

int D3DXInput::GetKeyUp()
{
	int tam = _keyUp;
	_keyUp = 0;
	return tam;
}

void D3DXInput::SetKeyDown(int key)
{
	_keyDown = key;
}

D3DXInput::~D3DXInput()
{
	if (_keyBoard)
	{
		_keyBoard->Unacquire();
		_keyBoard->Release();
	}

	if (_di)
		_di->Release();
}
